﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace Drawastick.Code
{
    public class IniHelper
    {
        [DllImport("kernel32", CharSet = CharSet.Ansi)]
        private static extern int GetPrivateProfileString(string section, string key, string defVal, StringBuilder retVal, int size, string filePath);

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);

        [DllImport("kernel32", EntryPoint = "GetPrivateProfileString")]
        private static extern uint GetPrivateProfileStringA(string section, string key, string def, Byte[] retVal, int size, string filePath);

        public static string getString(string path, string section, string key)
        {
            if (!File.Exists(path))
                File.Create(path).Close();
            var strs = File.ReadAllLines(path);
            var startline = 0;//第一个=可能开始的位置
            var endline = 0;//最后一个=出现的行
            for (int i = 0; i < strs.Length; i++)
            {
                if (strs[i] == "[" + section + "]")
                {
                    startline = i + 1;

                    bool done = false;
                    for (int end = i + 1; end < strs.Length; end++)
                    {
                        if (strs[end].StartsWith("[") && strs[end].EndsWith("]") && strs[end] != "[" + section + "]")
                        {
                            endline = end - 1;
                            done = true;
                            break;
                        }
                    }
                    if (!done)
                        endline = strs.Length-1;
                }
            }
            //得到start，end

            if (startline + endline != 0)

                for (int i = startline; i <= endline; i++)
                {
                    if (strs[i] != "" && strs[i].IndexOf("=") != -1)
                    {
                        var _key = strs[i].Split('=')[0];
                        var _value = strs[i].Split('=')[1];

                        if (_key == key)
                        {
                            return _value;//得到对应Value
                        }
                    }
                }
            return "";
        }

        public static void writeString(string path, string section, string key, string value)
        {
            if (!File.Exists(path))
                File.Create(path).Close();
            var strs = File.ReadAllLines(path);
            var list = strs.ToList();
            var index = list.FindIndex(item => item.Trim().StartsWith("[") && item.EndsWith("]") && item.TrimStart('[').TrimEnd(']') == section);
            var endline = 0;
            if (index == -1)
            {
                //不存在这个节
                list.Add("[" + section + "]");
                index = list.Count;
                list.Insert(index, key + "=" + value);//插入到节下面
                File.WriteAllLines(path, list);
                return;
            }
            else
            {
                //存在节
                for (int end = index + 1; end < strs.Length; end++)//寻找下一个
                {
                    if (strs[end].StartsWith("[") && strs[end].EndsWith("]") && strs[end] != "[" + section + "]")
                    {
                        endline = end - 1;//得到最后可能的位置
                        break;
                    }
                }
                if (endline == 0)
                {
                    endline = strs.Length - 1;//没找到下面的节，那就是已经到底了。
                }

                bool deal = false;
                for (int i = index + 1; i <= endline; i++)
                {
                    if (strs[i] != "" && strs[i].IndexOf("=") != -1)
                    {
                        var _key = strs[i].Split('=')[0];
                        var _value = strs[i].Split('=')[1];

                        if (_key == key)//找到存在的key
                        {
                            list[i] = _key + "=" + value;
                            deal = true;
                            break;
                        }
                    }
                }
                //找完了如果还没有
                if (!deal)
                {
                list.Insert(index, key + "=" + value);//插入到节下面

                }
                File.WriteAllLines(path, list);
            }
        }

        public static List<string> readSections(string iniFilename)
        {
            List<string> result = new List<string>();
            var strs = File.ReadAllLines(iniFilename);
            foreach (var item in strs)
            {
                if (item.Trim().StartsWith("[") && item.EndsWith("]"))
                {
                    result.Add(item.TrimStart('[').TrimEnd(']'));
                }
            }
            return result;
        }
    }
}